package com.permission.util;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.commons.collections.MapUtils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.permission.exception.ParamException;

/**
 * 对参数进行校验
 * @author jing
 *
 */
public class BeanValidator {
	
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	
	//对单个类进行校验
	public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);//自动地获取校验结果
        //如果当前参数有值，返回一个空的map值
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
        	//如果不是空值，说明有错误
            LinkedHashMap errors = Maps.newLinkedHashMap();	//保存错误信息和包含错误的字段
            Iterator iterator = validateResult.iterator();		
            while (iterator.hasNext()) {
            	//每次获取的ConstraintViolation都是一个校验结果 
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                //将错误的字段和错误信息放到errors
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

	//对多个对象（LIst）进行校验
    public static Map<String, String> validateList(Collection<?> collection) {
        Preconditions.checkNotNull(collection);		//判断是否为空，避免报异常
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next(); 
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }
    
    //这里对上面两个方法进行了封装，可以随便传入一个对象，任何校验使用这一个方法就可以了
    public static Map<String, String> validateObject(Object first, Object... objects) {
        //如果传入的objects不为空，则转为List再通过validateList进行校验
    	if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    //判断是否有异常
    //MapUtils：来自引入的工具类commons-collections、commons-codec
    public static void check(Object param) throws ParamException {
        Map<String, String> map = BeanValidator.validateObject(param);
        if (MapUtils.isNotEmpty(map)) {
            throw new ParamException(map.toString());
        }
    }
}
